package com.meixiang.view.wheel;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.entity.account.AddressEntity;
import com.meixiang.entity.account.AddressListEntity;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.wheel.mode.CityModel;
import com.meixiang.view.wheel.mode.DistrictModel;
import com.meixiang.view.wheel.mode.ProvinceModel;
import com.meixiang.view.wheel.widget.TosAdapterView;
import com.meixiang.view.wheel.widget.TosGallery;
import com.meixiang.view.wheel.widget.WheelView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地址选择Dialog
 * author：wangzuzhen on 2016/4/5 0005 15:13.
 */
public class AddressDialog extends Dialog {

    public interface AddressListener {
        public void getAddress(String address, String provinceId, String cityId, String districtId);
    }

    private Context context;
    private String title;
    private String rightTitle;
    private View view;
    private AddressListener addressListener;
    private WheelView mViewProvince = null;
    private WheelView mViewCity = null;
    private WheelView mViewDistrict = null;

    private TextView tv_right_title = null;
    private TextView mTitleTextView = null;
    private View mDecorView = null;

    private Activity mActivity;

    private NumberAdapter provinceAdapter;
    private NumberAdapter cityAdapter;
    private NumberAdapter districtAdapter;

    TosAdapterView.OnItemSelectedListener mListener = new TosAdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(TosAdapterView<?> parent, View view, int position, long id) {
            if (parent == mViewProvince) {
                updateCities();
            } else if (parent == mViewCity) {
                updateAreas();
            } else if (parent == mViewDistrict) {
//                mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[position];
//                mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
                mCurrentDistrictName = mCurrentDistrictList.get(position)
                        .getAreaName();
                mCurrentDistrictNameId = mCurrentDistrictList.get(position)
                        .getAreaId();
            }
        }

        @Override
        public void onNothingSelected(TosAdapterView<?> parent) {
        }
    };

    public AddressDialog(Activity mActivity, Context context, String title, String rightTitle, AddressListener addressListener) {
        super(context);
        this.mActivity = mActivity;
        this.context = context;
        this.addressListener = addressListener;
        this.title = title;
        this.rightTitle = rightTitle;
    }

    protected List<AddressEntity> mCurrentProviceList = new ArrayList<>();

    protected List<AddressEntity> mCurrentCitylist = new ArrayList<>();

    protected List<AddressEntity> mCurrentDistrictList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        view = LayoutInflater.from(context).inflate(R.layout.dialog_wheel_item, null);
        setContentView(view);
        super.onCreate(savedInstanceState);
        getAddressDatas("0");
        initDialog();
        mViewProvince = (WheelView) findViewById(R.id.wheel1);
        mViewCity = (WheelView) findViewById(R.id.wheel2);
        mViewDistrict = (WheelView) findViewById(R.id.wheel3);

        mViewProvince.setScrollCycle(true);
        mViewCity.setScrollCycle(true);

        mCurrentProviceList = getAddressDatas("0");
//        provinceAdapter = new NumberAdapter(mCurrentProviceList);
//        if (mCurrentProviceList.get(0).getAreaId() != "-1") {
//            mCurrentCitylist = getAddressDatas(mCurrentProviceList.get(0).getAreaId());
//            cityAdapter = new NumberAdapter(mCurrentCitylist);
//        }
//        if (mCurrentCitylist.get(0).getAreaId() != "-1") {
//            mCurrentDistrictList = getAddressDatas(mCurrentCitylist.get(0).getAreaId());
//            districtAdapter = new NumberAdapter(mCurrentDistrictList);
//        }

//        mViewProvince.setAdapter(provinceAdapter);
//        mViewCity.setAdapter(cityAdapter);
//        mViewDistrict.setAdapter(districtAdapter);

        mViewProvince.setSelection(0, true);
        mViewCity.setSelection(0, true);
        mViewDistrict.setSelection(0, true);

        mViewProvince.setOnItemSelectedListener(mListener);
        mViewCity.setOnItemSelectedListener(mListener);
        mViewDistrict.setOnItemSelectedListener(mListener);

        mViewProvince.setUnselectedAlpha(0.5f);
        mViewCity.setUnselectedAlpha(0.5f);
        mViewDistrict.setUnselectedAlpha(0.5f);

        mDecorView = getWindow().getDecorView();

        tv_right_title = (TextView) findViewById(R.id.tv_right_title);
        mTitleTextView = (TextView) findViewById(R.id.title);
        mTitleTextView.setText(title);
        tv_right_title.setText(rightTitle);
        tv_right_title.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {//完成
                // TODO Auto-generated method stub
//                Toast.makeText(context, mCurrentProviceName + mCurrentCityName + mCurrentDistrictName, Toast.LENGTH_SHORT).show();
//
//                addressListener.getAddress(mCurrentProviceName + "，" + mCurrentCityName + "，" + mCurrentDistrictName);
//                dismiss();

                addressListener.getAddress(mCurrentProviceName + "，" + mCurrentCityName + "，" + mCurrentDistrictName, mCurrentProviceNameId, mCurrentCityNameId, mCurrentDistrictNameId);
                dismiss();
            }
        });
    }

    private void initDialog() {
        setCancelable(false);
        getWindow().setGravity(Gravity.BOTTOM);
        getWindow().setBackgroundDrawableResource(R.color.transparent);
        int width = Tool.getWindowWith(context);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.width = width;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(params);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    // int pCurrent = 0;
    private void updateCities() {
        int pCurrent = mViewProvince.getSelectedItemPosition();
        // this.pCurrent = pCurrent;
        // if(mCurrentProviceName!=null && mProvinceDatas.length >= pCurrent) {
        // System.out.println(pCurrent+"--------------pCurrent------------");
        mCurrentProviceName = mCurrentProviceList.get(pCurrent).getAreaName();
        mCurrentCityNameId = mCurrentProviceList.get(pCurrent).getAreaId();
        mCurrentCitylist = getAddressDatas(mCurrentCityNameId);
        cityAdapter.setData(mCurrentCitylist);
        // cityAdapter.notifyDataSetChanged();
        mViewCity.setAdapter(cityAdapter);

        // mViewCity.setSelection(0);
        updateAreas();
        // }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getSelectedItemPosition();
        // System.out.println(pCurrent+"--------------pCurrent------------");
        if (mCurrentCitylist.size() >= pCurrent) {
            mCurrentCityName = mCurrentCitylist.get(pCurrent).getAreaName();
            mCurrentCityNameId = mCurrentCitylist.get(pCurrent).getAreaId();
            mCurrentDistrictList = getAddressDatas(mCurrentCityNameId);
            mCurrentDistrictName = mCurrentDistrictList.get(0).getAreaName();
            mCurrentDistrictNameId = mCurrentDistrictList.get(pCurrent).getAreaId();

            districtAdapter.setData(mCurrentDistrictList);
            // districtAdapter.notifyDataSetChanged();
            mViewDistrict.setAdapter(districtAdapter);
            // mViewDistrict.setSelection(0);
        }
    }


    @Override
    public void dismiss() {
        super.dismiss();
    }


    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    protected String[] mProvinceDataIds;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mCitisDatasMapIds = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mDistrictIdsDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();


    protected Map<String, String> mDistrictIdsMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    protected String mCurrentProviceNameId;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    protected String mCurrentCityNameId;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";
    protected String mCurrentDistrictNameId = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";

    /**
     * 解析省市区的XML数据
     */

//    protected void initProvinceDatas() {
//        List<ProvinceModel> provinceList = null;
//        AssetManager asset = context.getResources().getAssets();
//        try {
//            InputStream input = asset.open("province_data.xml");
//            // 创建一个解析xml的工厂对象
//            SAXParserFactory spf = SAXParserFactory.newInstance();
//            // 解析xml
//            SAXParser parser = spf.newSAXParser();
//            XmlParserHandler handler = new XmlParserHandler();
//            parser.parse(input, handler);
//            input.close();
//            // 获取解析出来的数据
//            provinceList = handler.getDataList();
//            //*/ 初始化默认选中的省、市、区
//            if (provinceList != null && !provinceList.isEmpty()) {
//                mCurrentProviceName = provinceList.get(0).getAreaName();
//                List<CityModel> cityList = provinceList.get(0).getChildern();
//                if (cityList != null && !cityList.isEmpty()) {
//                    mCurrentCityName = cityList.get(0).getAreaName();
//                    List<DistrictModel> districtList = cityList.get(0).getChildern();
//                    mCurrentDistrictName = districtList.get(0).getAreaName();
//                    mCurrentZipCode = districtList.get(0).getAreaId();
////                    mCurrentZipCode = districtList.get(0).getZipcode();
//                }
//            }
//            //*/
//            mProvinceDatas = new String[provinceList.size()];
//            for (int i = 0; i < provinceList.size(); i++) {
//                // 遍历所有省的数据
//                mProvinceDatas[i] = provinceList.get(i).getAreaName();
//                List<CityModel> cityList = provinceList.get(i).getChildern();
//                String[] cityNames = new String[cityList.size()];
//                for (int j = 0; j < cityList.size(); j++) {
//                    // 遍历省下面的所有市的数据
//                    cityNames[j] = cityList.get(j).getAreaName();
//                    List<DistrictModel> districtList = cityList.get(j).getChildern();
//                    String[] distrinctNameArray = new String[districtList.size()];
//                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
//                    for (int k = 0; k < districtList.size(); k++) {
//                        // 遍历市下面所有区/县的数据
//                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getAreaName(), districtList.get(k).getAreaId());
//                        // 区/县对于的邮编，保存到mZipcodeDatasMap
//                        mZipcodeDatasMap.put(districtList.get(k).getAreaName(), districtList.get(k).getAreaId());
//                        distrinctArray[k] = districtModel;
//                        distrinctNameArray[k] = districtModel.getAreaName();
//                    }
//                    // 市-区/县的数据，保存到mDistrictDatasMap
//                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
//                }
//                // 省-市的数据，保存到mCitisDatasMap
//                mCitisDatasMap.put(provinceList.get(i).getAreaName(), cityNames);
//            }
//        } catch (Throwable e) {
//            e.printStackTrace();
//        } finally {
//
//        }
//    }

    private List<AddressEntity> provinceList;

    //省
    public List<AddressEntity> getAddressDatas(String parentId) {
        HttpParams params = new HttpParams();
        params.put("parentId", parentId);
        HttpUtils.post(Config.SERVER_URL + "common/api/getChildren", params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                provinceList = AbJsonUtil.fromJson(result.optJSONArray("list").toString(), new TypeToken<ArrayList<AddressListEntity>>() {
                });
                //*/ 初始化默认选中的、省
                if (provinceList.size() > 0) {
//                    parentId= provinceList.get(0).getAreaId();
                } else {
                    AddressEntity model = new AddressEntity();
                    model.setAreaId("-1");
                    model.setAreaName("");
                    provinceList.add(model);
                }


            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(context, message);
                AddressEntity model = new AddressEntity();
                model.setAreaId("-1");
                model.setAreaName("");
                provinceList.add(model);
            }
        });

        return provinceList;
    }


    private class NumberAdapter extends BaseAdapter {
        int mHeight = 50;
        List<AddressEntity> mData = null;

        public NumberAdapter(List<AddressEntity> data) {
            mHeight = (int) Utils.dipToPx(context, mHeight);
            this.mData = data;
        }

        @Override
        public int getCount() {
            // return (null != mData) ? mData.length : 0;
            return (mData == null) ? 0 : mData.size();
        }

        @Override
        public View getItem(int position) {
            return getView(position, null, null);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setData(List<AddressEntity> mData) {
            this.mData = mData;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            WheelTextView textView = null;

            if (null == convertView) {
                convertView = new WheelTextView(context);
                convertView.setLayoutParams(new TosGallery.LayoutParams(-1,
                        mHeight));
                textView = (WheelTextView) convertView;
                textView.setTextSize(20);
                textView.setGravity(Gravity.CENTER);
            }
            String text = mData.get(position).getAreaName();
            if (null == textView) {
                textView = (WheelTextView) convertView;
            }
            textView.setText(text);
            return convertView;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
        }
        return super.onKeyDown(keyCode, event);
    }


}
